package com.heyi.nettylong.common;

import com.heyi.nettylong.common.protobuf.Command;
import com.heyi.nettylong.common.protobuf.Message;
import com.heyi.nettylong.common.util.MessageUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;

/**
 * 封闭消息的发送处理
 * @author dengfeng
 * @date 2022/4/117:56
 */
public class MessageHandler {

    protected ChannelHandlerContext ctx;

    public Message.MessageBase getMessage() {
        return msgBase;
    }

    protected Message.MessageBase msgBase;

    public MessageHandler(ChannelHandlerContext ctx, Message.MessageBase msgBase){
        this.ctx = ctx;
        this.msgBase = msgBase;
    }

    public ChannelFuture sendMessage(String jsonString){
        ChannelFuture cf = ctx.writeAndFlush(MessageUtil.build(msgBase.getMsgId(), msgBase.getClientId(), msgBase.getMsgId()>0 ? Command.CommandType.PUSH_DATA_BACK : Command.CommandType.PUSH_DATA, jsonString));
        if(msgBase.getMsgId() > 0) {
            msgBase = MessageUtil.build(msgBase.getClientId(), Command.CommandType.PUSH_DATA, msgBase.getData());
        }
        return cf;
    }
}
